package com.sinodoggo.shitcloud.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sinodoggo.shitcloud.commons.Result;
import com.sinodoggo.shitcloud.entity.Article;
import com.sinodoggo.shitcloud.entity.User;
import com.sinodoggo.shitcloud.service.IArticleService;
import com.sinodoggo.shitcloud.service.IBlogFileService;
import com.sinodoggo.shitcloud.service.ICommentService;
import com.sinodoggo.shitcloud.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sinodoggo
 * @since 2022-11-26
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService articleService;
    @Resource
    private ICommentService commentService;

    @GetMapping
    public Result getAllArticles() {
        final List<Article> articleList = articleService.list();
        return Result.success(articleList);
    }

    @GetMapping("/{id}")
    public Result getArticleById(@PathVariable Integer id) {
        final Article article = articleService.getById(id);
        return Result.success(article);
    }

    @PostMapping
    public Result saveOrUpdate(@RequestBody Article article) {
        if (null == article.getId()) {
            final User currentUser = TokenUtils.getCurrentUser();
            final String userName = currentUser.getUserName();
            final Integer userId = currentUser.getId();
            article.setUserId(userId);
            article.setUploader(userName);
        }
        articleService.saveOrUpdate(article);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteArticleById(@PathVariable Integer id) {
        articleService.removeById(id);
        commentService.removeCommentsByArticleId(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatchByIds(@RequestBody List<Integer> ids) {
        articleService.removeBatchByIds(ids);
        return Result.success();
    }

    @GetMapping("/page")
    public Result pageDivision(@RequestParam Integer pageNumber,
                               @RequestParam Integer pageSize,
                               @RequestParam(value = "name", defaultValue = "") String name,
                               @RequestParam(value = "uploader", defaultValue = "") String uploader) {
        Page<Article> page = new Page<>(pageNumber, pageSize);
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        if (!StrUtil.isBlank(name)) {
            wrapper.like("name", name);
        }
        if (!StrUtil.isBlank(uploader)) {
            wrapper.like("uploader", uploader);
        }
        return Result.success(articleService.page(page, wrapper));
    }
}

